import { useEffect } from 'react';
import { useAppDispatch, useAppSelector } from './useRedux';
import { addColumn, getColumns, setColumns, setTaskItemColumns } from '@/redux/columns/columnsSLice';
import Sortable from 'sortablejs';
import { moveTask, moveTaskColumn } from '@/redux/tasks/tasksSlice';

const useColumns = () => {
  const dispatch = useAppDispatch();
  const { columns, status } = useAppSelector(state => state.columns)
  const { selectedProjectId } = useAppSelector(state => state.projects)

  useEffect(() => {
    if (selectedProjectId) dispatch(getColumns(selectedProjectId));
  }, [dispatch, selectedProjectId]);

  const setTaskAfterMovement = (tasks: Task[], collId: number) => {
    dispatch(setTaskItemColumns({ collId, tasks }));
  }

  function getPinnedTasksCount(column: Column[], id: number) {
    const foundColumn = column.find(col => col.id === id);
    if (!foundColumn) return 0;
    return foundColumn.tasks.filter(task => task.pinned).length;
  }

  const moveTaskItem = ({ oldIndex = 0, newIndex = 0, item, from }: Sortable.SortableEvent) => {
    const oldPinnedCount = getPinnedTasksCount(columns, +from.id);
    const newPinnedCount = getPinnedTasksCount(columns, +from.id);
    dispatch(moveTask({
      taskId: +item.id,
      colId: +from.id,
      taskNewIndex: newIndex + newPinnedCount,
      taskOldIndex: oldIndex + oldPinnedCount
    }))
  };

  const handleSortColumns = (columns: Column[]) => {
    dispatch(setColumns(columns))
  }

  const moveTaskItemColumn = ({ item, from, to, newIndex = 0, oldIndex = 0 }: Sortable.SortableEvent) => {
    const oldPinnedCount = getPinnedTasksCount(columns, +from.id);
    const newPinnedCount = getPinnedTasksCount(columns, +to.id);
    dispatch(moveTaskColumn({
      taskId: +item.id,
      oldColId: +from.id,
      newColId: +to.id,
      taskNewIndex: newIndex + newPinnedCount,
      taskOldIndex: oldIndex + oldPinnedCount
    }))
  }

  const onAddNewColumn = (value: string) => {
    dispatch(addColumn(value))
  }


  return {
    columns,
    status,
    setTaskAfterMovement,
    handleSortColumns,
    moveTaskItem,
    moveTaskItemColumn,
    onAddNewColumn
  };
};

export default useColumns;